Strict

#TEXT_FILES="*.txt|*.xml|*.json|*.lua"

Import mojo
Import monkeylua
Import monkeylua.mojolua

Function Main:Int()
	New LuaApp()
	Return 0
End

Class LuaApp Extends App
	Global shouldQuit:Bool = False
	Global console:StringList = New StringList
	Global showConsole:Bool = False
	Global lastUpdate:Int = 0
	Global lastRender:Int = 0
	
	Field state:LuaState
	
	Method OnCreate:Int()
		SetUpdateRate(60)
		state = New LuaState
		RegisterMojoLua(state)
		RegisterGlobalFunction(state, "Quit", New QuitFunc)
		RegisterGlobalFunction(state, "Print", New PrintFunc)
		LoadScript()
		If state.DoString("Create()") <> LUA_OK Then Print state.ToString(-1)
		If shouldQuit Then Error ""
		Return 0
	End
	
	Method OnUpdate:Int()
		Local now:Int = Millisecs()
		Local delta:Int = now-lastUpdate
		lastUpdate = now
#If CONFIG="debug" Then
		If KeyHit(KEY_F5) Then LoadScript()
		If KeyHit(KEY_TAB) Then showConsole = Not showConsole
#End
		If state.DoString("Update("+delta+")") <> LUA_OK Then Print state.ToString(-1)
		If shouldQuit Then Error ""
		Return 0
	End
	
	Method OnRender:Int()
		Local now:Int = Millisecs()
		Local delta:Int = now-lastRender
		lastRender = now
#If CONFIG="debug" Then
		FPSCounter.Update()
#End
		Cls
		SetColor(255,255,255)
		If state.DoString("Render("+delta+")") <> LUA_OK Then Print state.ToString(-1)
		If shouldQuit Then Error ""
#If CONFIG="debug" Then
		SetColor(255,255,255)
		SetAlpha(1)
		FPSCounter.Draw()
		SetColor(0,255,0)
		If showConsole Then
			Local y:Int = DeviceHeight()-15
			For Local str:String = EachIn console
				DrawText(str, 0, y)
				y -= 15
			Next
		End
#End
		Return 0
	End
	
	Method LoadScript:Void()
		If state.DoString(LoadString("game.lua")) <> LUA_OK Then Print state.ToString(-1)
	End
End

Class QuitFunc Extends MonkeyFunction
	Method Func:Int(state:LuaState)
		LuaApp.shouldQuit = True
		Return 0
	End
End

Class PrintFunc Extends MonkeyFunction
	Method Func:Int(state:LuaState)
		Local count:Int = state.GetTop()
		For Local i:Int = 1 To count
			If Not state.IsNil(i) Then
				LuaApp.console.AddFirst(state.ToString(i))
			End
		Next
		While LuaApp.console.Count() > 20
			LuaApp.console.RemoveLast()
		End
		state.PushNil()
		Return 1
	End
End

Class FPSCounter
	Global fpsCount:Int
	Global startTime:Int
	Global totalFPS:Int

	Function Update:Void()
		If Millisecs() - startTime >= 1000
			totalFPS = fpsCount
			fpsCount = 0
			startTime = Millisecs()
		Else
			fpsCount+=1
		End
	End

	Function Draw:Void(x% = 0, y% = 0, ax# = 0, ay# = 0)
		DrawText("FPS: " + totalFPS, x, y, ax, ay)
	End
End
